package com.google.android.mypetrol;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;

public class PetrolDetailActivity extends Activity {
	
	private PetrolDetail mPetrolDetail;
	private int mMode;
	private int mIndex;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        
        Intent intent = getIntent();
        mMode = intent.getIntExtra(MyPetrol.ITEM_TYPE, MyPetrol.MODE_NEW);
        mIndex = intent.getIntExtra(MyPetrol.ITEM_INDEX, 0);
        
        mPetrolDetail = new PetrolDetail(this);
        setContentView(mPetrolDetail);
        
        if (mMode == MyPetrol.MODE_MODIFY) {
			Cursor c = getContentResolver().query(Provider.CONTENT_URI, null, null, null, "datetime");
			c.moveToPosition(mIndex);
			mPetrolDetail.setDate(c.getLong(1));
			mPetrolDetail.setCost(c.getInt(2), c.getFloat(3));
			c.close();
        }
        
        mPetrolDetail.setOnOkClickListener(new View.OnClickListener(){
			public void onClick(View v) {
				storeDataToDB();
				finish();
			}
        });
        
        mPetrolDetail.setOnCancelClickListener(new View.OnClickListener(){
			public void onClick(View v) {
				finish();
			}
        });
    }
    
    private void storeDataToDB() {
		int total = mPetrolDetail.getTotal();
		float price = mPetrolDetail.getPrice();
		long dateMillion = mPetrolDetail.getDateMillion();
		String year = mPetrolDetail.getYear();
		String month = mPetrolDetail.getMonth();
		String date = mPetrolDetail.getDate();
		
		ContentValues values = new ContentValues();
		values.put("total", total);
		values.put("price", price);
		values.put("datetime", dateMillion);
		values.put("year", year);
		values.put("month", month);
		values.put("date", date);
		
		ContentResolver r = getContentResolver();
		if (mMode == MyPetrol.MODE_MODIFY) {
			Cursor c = r.query(Provider.CONTENT_URI, null, null, null, "datetime");
			c.moveToPosition(mIndex);
			c.updateLong(1, dateMillion);
			c.updateInt(2, total);
			c.updateFloat(3, price);
			c.updateString(4, year);
			c.updateString(5, month);
			c.updateString(6, date);
			c.commitUpdates();
			c.close();
		}else {
			r.insert(Provider.CONTENT_URI, values);
		}
	}
}